import body_movement
from utils import plot_anything,detect_no_signal
import filter
import find_peaks_template
import read_data
import matplotlib.pyplot as plt
import time
import numpy as np
from scipy import signal


file_name ='20210720_1nf_01hz_10hz_30db_200hz_16bit_屏住呼吸测试片段.txt'
sample_rate = 200
window_size = 25*sample_rate

#mov avg
variance_detect_window_size_scale = 3
high_mov_avg_raise_proportion = 1.2
low_mov_avg_raise_proportion = 0.7
high_peak_detect_proportion = 1.65
low_peak_detect_proportion = 0.2
regular_variance = 0.6

#nornal
movement_time_proportion_threshold = 5.0
deep_sleep_continuous_static_threshold = 360
smooth_duration_threshold = 0.2
remove_invalid_threshold = 0.2


bcg_low_cutoff=10.0

#无信号片段的最大幅值
no_signal_val =0.1

#体动拒绝比例
body_movemet_reject_ratio = 0.1


if __name__ == "__main__":
    bcg_data = read_data.read_data_txt(file_name)
    #bcg_data =read_data.read_data_mat(file_name,'ECG')
    #temp =bcg_data[840000:850000]
    #bcg_filt = filter.heart_filter(bcg_data, 1.0, 10, sample_rate)

    window_accept =[]
    for i in range(int(len(bcg_data)/window_size)):
        print(i)
        data = bcg_data[i*window_size:(i+1)*window_size]
        # no_signal = detect_no_signal(data,sample_rate,no_signal_val)
        # if no_signal==0:
        #     window_accept.append(0)
        #     print("no signal")
        #     continue

        # try:
        #     body_move = body_movement.get_body_movements_from_raw_data(data, sample_rate, high_mov_avg_raise_proportion,
        #         low_mov_avg_raise_proportion, high_peak_detect_proportion,
        #         low_peak_detect_proportion,smooth_duration_threshold, remove_invalid_threshold)
        # except:
        #     window_accept.append(0)
        #     print("body ratio")
        #     continue
        #
        # body_move_ratio = body_movement.get_body_movement_ratio(body_move)
        # #plot_anything([bcg_data, body_move])
        # if body_move_ratio >body_movemet_reject_ratio:
        #     window_accept.append(0)
        #     print("body ratio",body_move_ratio)
        #     continue
        try:
            heart_rate, bcg_filt, max_val_pos, val, ignore_num =find_peaks_template.get_heart_rate(data,sample_rate,bcg_low_cutoff)
        except:
            window_accept.append(0)
            print("no template")
            continue

        if ignore_num ==0:
            window_accept.append(0)
            print("no template")
            continue
        window_accept.append(1)
        print("heart rate",heart_rate)

        plt.plot(bcg_filt)
        plt.scatter(max_val_pos,val,color='red')
        plt.show()

    move_num = 0
    for i in window_accept:
        if i == 1:
            move_num += 1
    accept_ratio = move_num/len(window_accept)

    print(accept_ratio)
    # plt.subplot(211)
    # plt.plot(bcg_data)
    # plt.subplot(212)
    # x = [i for i in range(len(window_accept))]
    # plt.scatter(x,window_accept)
    # plt.show()